/* 
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.avdheshyadav.p4j.sample.client.presenter;

import java.util.List;

import org.gwt.mosaic.ui.client.table.FixedWidthGrid;

import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;

import com.avdheshyadav.p4j.sample.shared.data.Book;
import com.avdheshyadav.p4j.sample.shared.rpc.BooksResult;
import com.avdheshyadav.p4j.sample.shared.rpc.FetchBooksAction;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class BookListPresenter extends WidgetPresenter<BookListPresenter.Display>
{
	public interface Display extends WidgetDisplay
	{
		public FixedWidthGrid getDataTable();
	}

	private DispatchAsync dispatcher;
	private EventBus eventBus;

	@Inject
	public BookListPresenter(BookListPresenter.Display display, EventBus bus, DispatchAsync dispatcher)
	{
		super(display,bus);
		this.dispatcher = dispatcher;
	}

	@Override
	protected void onBind() 
	{

		dispatcher.execute(new FetchBooksAction(true), new AsyncCallback<BooksResult>() {
			public void onFailure(Throwable caught) {
				Window.alert("Error Occured during fetching of Books from the Server");
			}

			public void onSuccess(BooksResult result) {
				List<Book> books = result.getBooks();
				FixedWidthGrid dataTable = display.getDataTable();
				dataTable.resizeRows(books.size());
				int i = 0;
				for(Book book : books)
				{
					dataTable.setText(i, 0, book.getIsbn());
					dataTable.setText(i, 1, book.getTitle());
					dataTable.setText(i, 2, String.valueOf(book.getAuthorId()));
					i = i + 1;
				}
			}
		});
	}

	@Override
	protected void onUnbind() 
	{
		// Nothing to do
	}

	@Override
	protected void onRevealDisplay()
	{
		// Nothing to do
	}
}
